package com.vcs.frm.dao;

import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.HibernateTemplate;

import com.vcs.frm.domain.Jobseeker;
import com.vcs.frm.domain.User;
import com.vcs.frm.domain.UserRole;
import com.vcs.frm.utils.Constants;

public class JobseekerDaoImpl implements JobseekerDao {

	private final Logger log = Logger.getLogger(this.getClass());
	private SessionFactory sessionFactory;
	private HibernateTemplate hibernateTemplate;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
		this.hibernateTemplate = new HibernateTemplate(sessionFactory);
	}

	@Override
	public void saveJobseeker(Jobseeker jobseeker, String password) throws DataAccessException {

		/*
		 * 2> Insert record in Users table & user Roles table, set role to
		 * Jobseeker
		 */
		User user = new User(jobseeker.getEmail(), password, 1);
		Long userId = (Long) hibernateTemplate.save(user);
		UserRole role = new UserRole(userId, Constants.ROLE_JOBSEEKER);
		hibernateTemplate.save(role);
		
		/* 1> Save jobseeker */
		jobseeker.setJobseekerId(user.getUserId());
		Long jobseekerId = (Long) hibernateTemplate.save(jobseeker);
		log.info("Jobseeker Created with profile id :" + jobseekerId);
	}

	@Override
	public Jobseeker getJobseekerByProfileId(Long profileId) {

		Session session = sessionFactory.getCurrentSession();
		Jobseeker js = null;
		js = (Jobseeker) session.load(Jobseeker.class, profileId);
		js.getAddress();
		js.getCurrentLocation();
		return js;
	}
}
